package com.yohann.order_service.controller;

import com.yohann.order_service.service.OrdersService;
import com.yohann.order_service.service.WeChatPayService;
import com.yohann.utils.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>
 * 微信支付 前端控制器
 * </p>
 *
 * @author Yohann
 * @since 2020/11/13 15:34
 */
@Api(tags = "微信支付")
@RestController
@RequestMapping("/WeChatPay")
public class WeChatPayController {
    @Autowired
    private WeChatPayService weChatPayService;

    @Autowired
    private OrdersService ordersService;

    /**
     * 生成支付二维码
     *
     * @param orderId 订单id
     * @return 二维码字符串
     */
    @ApiOperation("生成支付二维码")
    @GetMapping("createNative/{orderId}")
    public Result getQrCode(@ApiParam("订单id") @PathVariable String orderId) {
        Map map = weChatPayService.getQrCode(orderId);

        return Result.ok().data(map);
    }

    /**
     * 查询支付状态
     *
     * @param orderId 订单id
     * @return 支付状态
     */
    @ApiOperation("查询支付状态")
    @GetMapping("getPayStatue/{orderId}")
    public Result getPayStatus(@ApiParam("订单id") @PathVariable String orderId) {
        Map<String, String> map = weChatPayService.getPayStatus(orderId);

        if (map.isEmpty()) {
            return Result.error().message("支付失败");
        }

        //如果返回不为空，查询支付状态
        if ("SUCCESS".equals(map.get("trade_state"))) {
            //修改订单状态
            return Result.state(weChatPayService.updateOrderStatue(map)).message("支付成功");
        }

        return Result.ok().code(25000).message("支付中");
    }
}